// 聊天功能
class ChatApp {
    constructor() {
        this.messagesContainer = document.getElementById('chatMessages');
        this.messageInput = document.getElementById('messageInput');
        this.sendButton = document.getElementById('sendButton');
        this.typingIndicator = document.getElementById('typingIndicator');
        this.fileUpload = document.getElementById('fileUpload');
        this.uploadProgress = document.getElementById('uploadProgress');
        this.progressText = document.getElementById('progressText');
        
        this.currentFile = null;
        
        this.initEventListeners();
        this.addWelcomeMessage();
    }

    initEventListeners() {
        this.sendButton.addEventListener('click', () => this.sendMessage());
        this.messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                this.sendMessage();
            }
        });
        
        // 文件上传事件
        this.fileUpload.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                this.currentFile = e.target.files[0];
                this.messageInput.placeholder = `已选择: ${this.currentFile.name} - 输入描述或直接发送`;
                this.addMessage(`📎 已选择文件: ${this.currentFile.name}`, true);
            }
        });
        
        // 自动调整输入框高度
        this.messageInput.addEventListener('input', () => {
            this.messageInput.style.height = 'auto';
            this.messageInput.style.height = Math.min(this.messageInput.scrollHeight, 120) + 'px';
        });
    }

    addWelcomeMessage() {
        const welcomeMessage = "您好！我是IT Assistant，您的智能IT治理助手。我可以帮助您：\n\n• 解答IT技术问题\n• 提供安全建议\n• 分析系统配置\n• 协助决策制定\n• 解析账号密码文件\n\n请告诉我您需要什么帮助？";
        this.addMessage(welcomeMessage, false);
    }

    async sendMessage() {
        const message = this.messageInput.value.trim();
        
        // 如果没有消息也没有文件，直接返回
        if (!message && !this.currentFile) return;
        
        // 添加用户消息
        if (message) {
            this.addMessage(message, true);
        }
        
        this.messageInput.value = '';
        this.messageInput.style.height = '60px';
        this.messageInput.placeholder = '输入您的问题或上传文件...（Enter发送，Shift+Enter换行）';
        
        // 禁用输入
        this.setInputState(false);
        
        // 显示打字指示器
        this.showTypingIndicator();
        
        try {
            let response;
            
            if (this.currentFile) {
                // 有文件：上传文件并解析
                response = await this.uploadAndParseFile(message);
            } else {
                // 没有文件：普通聊天
                response = await this.callDeepSeekAPI(message);
            }
            
            if (response.success) {
                this.addMessage(response.response, false);
                
                // 如果是文件解析，显示保存按钮
                if (response.parse_result && response.parse_result.credentials) {
                    this.showSaveCredentialsButton(response);
                }
            } else {
                this.addMessage(`抱歉，出现错误：${response.error}`, false);
            }
        } catch (error) {
            this.addMessage('网络错误，请检查连接后重试', false);
            console.error('API调用错误:', error);
        } finally {
            this.hideTypingIndicator();
            this.setInputState(true);
            this.currentFile = null;
            this.fileUpload.value = '';
            this.messageInput.focus();
        }
    }

    async uploadAndParseFile(message) {
        const formData = new FormData();
        formData.append('file', this.currentFile);
        
        if (message) {
            formData.append('message', message);
        }
        
        // 显示上传进度
        this.showUploadProgress();
        
        try {
            const response = await fetch('/api/deepseek/chat/', {
                method: 'POST',
                headers: {
                    'X-CSRFToken': this.getCookie('csrftoken')
                },
                body: formData
            });
            
            const result = await response.json();
            this.hideUploadProgress();
            
            if (result.success) {
                let responseText = `📁 文件 "${this.currentFile.name}" 解析完成！\n\n`;
                responseText += `共发现 ${result.parse_result.credentials?.length || 0} 条账号记录\n\n`;
                
                // 显示解析结果摘要
                if (result.parse_result.credentials) {
                    result.parse_result.credentials.slice(0, 3).forEach((cred, index) => {
                        responseText += `${index + 1}. ${cred.location} - ${cred.device_name}\n`;
                        responseText += `   用户: ${cred.username} | 状态: ${cred.status}\n\n`;
                    });
                    
                    if (result.parse_result.credentials.length > 3) {
                        responseText += `... 还有 ${result.parse_result.credentials.length - 3} 条记录\n\n`;
                    }
                }
                
                responseText += "请点击下方按钮保存到数据库";
                
                return {
                    ...result,
                    response: responseText
                };
            } else {
                return result;
            }
        } catch (error) {
            this.hideUploadProgress();
            throw error;
        }
    }

    async callDeepSeekAPI(message) {
        const response = await fetch('/api/deepseek/chat/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': this.getCookie('csrftoken')
            },
            body: JSON.stringify({ message: message })
        });
        
        return await response.json();
    }

    showSaveCredentialsButton(response) {
        const saveButton = document.createElement('button');
        saveButton.className = 'save-credentials-btn';
        saveButton.innerHTML = '💾 保存到数据库';
        saveButton.onclick = () => this.saveCredentials(response);
        
        const messageDiv = document.createElement('div');
        messageDiv.className = 'message ai-message';
        messageDiv.appendChild(saveButton);
        
        this.messagesContainer.appendChild(messageDiv);
        this.scrollToBottom();
    }

    async saveCredentials(response) {
        try {
            this.addMessage('正在保存到数据库...', false);
            
            const saveResponse = await fetch('/api/credentials/save/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': this.getCookie('csrftoken')
                },
                body: JSON.stringify({
                    credentials: response.parse_result.credentials,
                    file_info: response.file_info
                })
            });
            
            const result = await saveResponse.json();
            
            if (result.success) {
                this.addMessage(`✅ 保存成功！共保存 ${result.saved_count} 条记录到数据库`, false);
            } else {
                this.addMessage(`❌ 保存失败: ${result.error}`, false);
            }
        } catch (error) {
            this.addMessage('❌ 保存过程中出现网络错误', false);
            console.error('保存错误:', error);
        }
    }

    showUploadProgress() {
        this.uploadProgress.style.display = 'block';
        let progress = 0;
        const interval = setInterval(() => {
            progress += 10;
            if (progress <= 90) {
                this.progressText.textContent = `${progress}%`;
            }
        }, 200);
        
        this.progressInterval = interval;
    }

    hideUploadProgress() {
        if (this.progressInterval) {
            clearInterval(this.progressInterval);
        }
        this.progressText.textContent = '100%';
        setTimeout(() => {
            this.uploadProgress.style.display = 'none';
        }, 500);
    }

    addMessage(text, isUser) {
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${isUser ? 'user-message' : 'ai-message'}`;
        
        const bubble = document.createElement('div');
        bubble.className = `message-bubble ${isUser ? 'user-bubble' : 'ai-bubble'}`;
        
        // 处理换行和基本格式化
        const formattedText = text.replace(/\n/g, '<br>');
        bubble.innerHTML = formattedText;
        
        messageDiv.appendChild(bubble);
        this.messagesContainer.appendChild(messageDiv);
        
        // 滚动到底部
        this.scrollToBottom();
    }

    showTypingIndicator() {
        this.typingIndicator.style.display = 'block';
        this.scrollToBottom();
    }

    hideTypingIndicator() {
        this.typingIndicator.style.display = 'none';
    }

    setInputState(enabled) {
        this.messageInput.disabled = !enabled;
        this.sendButton.disabled = !enabled;
        this.fileUpload.disabled = !enabled;
    }

    scrollToBottom() {
        this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight;
    }

    getCookie(name) {
        let cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            const cookies = document.cookie.split(';');
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i].trim();
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    new ChatApp();
});